package cn.blogsx.jdbc;

import cn.blogsx.domain.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class JdbcDemo02 {
    public static void main(String[] args) {
        List<User> all = findAll();
        all.stream().forEach(System.out::println);
    }
    public static List<User> findAll() {
        List<User> userList = new ArrayList<User>();
        Connection conn=null;
        Statement stmt=null;
        try {
            //1、注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest", "root", "root");
            //3.定义sql
            String sql = "select * from user";
            //4.获取执行sql的对象
            stmt = conn.createStatement();

            //5.执行sql
            ResultSet resultSet = stmt.executeQuery(sql);

            //6.遍历结果集，封装对象，装载集合
            User user=null;
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                String sex = resultSet.getString("sex");
                user= new User(id,username,password,sex);
                userList.add(user);
            }



        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return userList;
    }
}
